package com.qf.shiro;

import com.alibaba.druid.util.StringUtils;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    DtsAdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DtsAdmin admin = (DtsAdmin) principalCollection.getPrimaryPrincipal();
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.findRolesByRoleIds(roleIds);
        Set<String> perms = permissionService.findPermsByRoleIds(roleIds);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名和密码
        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());
        // 根据用户名 查询用户对象(数据库)
        DtsAdmin admin = adminService.findByUsername(username);
        //校验用户信息(如果有问题，则抛出异常)
        if(admin == null) {
            throw new UnknownAccountException("未知的用户");
        }
        if(admin.getDeleted()) {
            throw new LockedAccountException("账户已锁定");
        }
        // 数据库密码，采用的 bcrypt加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(StringUtils.isEmpty(password) || !passwordEncoder.matches(password, admin.getPassword())) {
            throw new CredentialsException("密码错误");
        }
        /**
         * 密码： 在返回后， 框架中还会对密码进行校验
         */
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin, password, username);

        return authenticationInfo;
    }
}
